//
//  WDRootViewController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/12.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDRootController.h"

@interface WDRootController ()

@end

@implementation WDRootController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.firstCome = YES;
    
    self.dataArray = [NSMutableArray array];
    
    //[self loadUI];
    
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self checkNewWorking];
    
    [self preferredStatusBarStyle];
}

- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //查看通知的个数
    [self sendCountRequest];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
}

- (void)clickNavLeft
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@PostString object:NSStringFromClass([self class])];
    //打开抽屉效果
    [self.mm_drawerController openDrawerSide:MMDrawerSideLeft
                                    animated:YES
                                  completion:^(BOOL finished) {
                                      
                                  }];
}

//示例
- (void)loadUI
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
    
    self.tableView.estimatedRowHeight = 100;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self sendRequestDataWithURLStr:@"" Model:@"" parameters:nil succeed:nil filed:nil];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [self sendRequestDataWithURLStr:@"" Model:@"" parameters:nil succeed:nil filed:nil];
    }];
}

#pragma mark - 发请求
- (void)sendRequestDataWithURLStr:(NSString *)URLStr Model:(NSString *)className parameters:(NSDictionary *)parameters succeed:(succeed)succeed filed:(filed)filed
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    __weak typeof (self)weakSelf = self;
    
    [manager POST:URLStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        weakSelf.placeView.hidden = YES;
        
        weakSelf.firstCome = NO;
        
        [weakSelf.tableView.mj_header endRefreshing];
        
        [weakSelf.tableView.mj_footer endRefreshing];
        
        weakSelf.page = [responseObject[@"current_page"] integerValue];
        
        weakSelf.totalPage = [responseObject[@"total_page"] integerValue];
        
        if (weakSelf.page == 1) {//下拉刷新，清除所有数据
            [weakSelf.dataArray removeAllObjects];
        }
        //添加新数据
        [weakSelf.dataArray addObjectsFromArray:[NSClassFromString(className) mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]];
        
        if (weakSelf.page > weakSelf.totalPage) {
            
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        } else {
            
            weakSelf.page++;
            
            [weakSelf.tableView reloadData];
        }
        
        if (succeed)
        {
            succeed(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        
        [weakSelf.dataArray removeAllObjects];
        [weakSelf.tableView reloadData];
        
        [self showPlaceViewWithImageName:@"icon_loadFailed" status:@"网络连接异常"];
//        if (error) {
//            
//            filed(error);
//        }
    }];
}

- (void)sendCountRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLGetNotice];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"当前通知个数 = %@", responseObject[@"count"]);
        
        if ([responseObject[@"count"] boolValue]) {//有通知
            
            [self setNavLeftBtnWithAction:@selector(clickNavLeft) leftBtnImage:@"icon-baidian" leftBtnSelImage:@"icon-baidian"];
            
            //设置图标个数
            [UIApplication sharedApplication].applicationIconBadgeNumber = [responseObject[@"count"] integerValue];
            
            [GeTuiSdk setBadge:[responseObject[@"count"] integerValue]];
            
        } else {//没有通知
            
            [self setNavLeftBtnWithAction:@selector(clickNavLeft) leftBtnImage:@"actionbar" leftBtnSelImage:@"actionbar"];
            
            //设置图标个数
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            
            [GeTuiSdk setBadge:0];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@", error);
        
    }];
    
}

//加载占位图
- (WDPlaceholderView *)loadPlaceViewWithImageName:(NSString *)imageName status:(NSString *)status
{
    WDPlaceholderView *placeView = [WDPlaceholderView placeholderViewWithImageName:imageName status:status];
    [self.view addSubview:placeView];
    placeView.backgroundColor = WDBackColor;
    placeView.hidden = NO;
    
    [placeView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(100);
        make.left.equalTo(25);
        make.right.equalTo(-25);
        make.bottom.equalTo(0);
    }];
    
    return placeView;
}

//移除占位图
- (void)hideLoadView
{
    self.placeView.hidden = YES;
}

//改变展位图
- (void)showPlaceViewWithImageName:(NSString *)imageName status:(NSString *)status
{
    self.placeView.hidden = NO;
    
    self.placeView.imageName = imageName;
    
    self.placeView.status = status;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

#pragma - mark - 设置网络状态监听
/**
 typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
 AFNetworkReachabilityStatusUnknown          = -1,//未识别的网络
 AFNetworkReachabilityStatusNotReachable     = 0,//不可达的网络
 AFNetworkReachabilityStatusReachableViaWWAN = 1,//2G,3G,4G...
 AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi网络
 */
- (void)checkNewWorking
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                
                [WDPromptBox showPromptBoxWithMassage:@"未识别的网络"];
                
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                [WDPromptBox showPromptBoxWithMassage:@"网络连接中断"];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                
                break;
            default:
                break;
        }
     
     }];
    
    //开始监听
    [manager startMonitoring];
    
}

@end
